package com.pengweiwei.androidzygote.functions.base.mvp;


import com.pengweiwei.androidzygote.functions.httprequest.UserBean;
import com.pengweiwei.androidzygote.main.UrlCenter;
import com.putong35.common.baseactfrag.CompState;
import com.putong35.common.baseactfrag.activity.RecyclerViewBaseActivity;
import com.putong35.common.baseactfrag.mvp.BasePresenter;
import com.putong35.common.baseactfrag.mvp.IMvpListView;
import com.putong35.common.baseactfrag.refreshable.IRefreshable;
import com.putong35.common.httprequest.IHttpRequest;
import com.putong35.common.httprequest.UrlParams;
import com.putong35.common.httprequest.app.MyHttpRequest;
import com.putong35.common.httprequest.responsecallbacks.ListBeanResponseListener;
import com.putong35.common.utils.SLog;

import java.util.List;

public class ListActPresenter extends BasePresenter<IMvpListView> {
    private RecyclerViewBaseActivity mActContext;

    private IRefreshable mRefreshable;

    /**
     * 使用默认的数据解析器
     *
     * @param context
     */
    public ListActPresenter(RecyclerViewBaseActivity context) {
        mActContext = context;
        if (context instanceof IRefreshable) {
            mRefreshable = (IRefreshable) context;
        }
    }


    @Override
    public void attachView(IMvpListView mvpView) {
        super.attachView(mvpView);
        init();
    }

    @Override
    public void detachView() {
        super.detachView();
    }

    void invalidate(){
        init();
        mActContext.getAdapter().getData().clear();
        getMvpView().clearList();
    }

    void init() {
        mPage = 0;
        mResponseListener = new ListBeanResponseListener<UserBean>(UserBean.class) {
            @Override
            public void onSuccess(List<UserBean> beanList) {
                SLog.e(beanList.toString());
                if (beanList.size() > 0) {
                    mActContext.getAdapter().getData().addAll(beanList);
                    getMvpView().insertListItem(beanList);
                }


            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                getMvpView().showToast(strMsg);
                mActContext.setState(CompState.EMPTY_ERROR);

            }
        };

    }


    private int mPage = 0;
    private ListBeanResponseListener<UserBean> mResponseListener;


    public void loadNextPage() {
        if (mResponseListener.hasNextPage()) {
            mPage++;
            IHttpRequest request = new MyHttpRequest(mActContext);
            UrlParams params = new UrlParams();
            params.put("file_name", "list_data");
            params.put("page_no", mPage);
            request.get(UrlCenter.URL_NORMAL_DATA, params, mResponseListener);
        }
    }

    public boolean hasNextPage() {
        return mResponseListener.hasNextPage();
    }

    public void reload() {
        invalidate();
        loadNextPage();
    }

}
